package sa.com.sure.ejtimaa.database;


import sa.com.sure.ejtimaa.common.AppHelper;
import sa.com.sure.ejtimaa.model.SettingInfo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;


public class Settings {

	private DataBaseHelper dbHelper;
	
	public static final String TABLE_Name = "Settings";
	
    public static final String KeyField = "Key"; 
    public static final String ValueField = "Value";
    
    private String[] allColumns = { KeyField, ValueField  };
    
    Cursor cursor = null;
    
    public Settings(Context context)  {
 		dbHelper = new DataBaseHelper(context);
 		dbHelper.createDataBase();
 	}
        
    public static Settings Instance = new Settings(AppHelper.getAppContext());
    
	public void open() throws SQLException {
		dbHelper.openDataBase();
	}
	
	public void close() {
		if(cursor!=null && !cursor.isClosed())
			cursor.close();
		dbHelper.close();
	}
	
	public void addItem(SettingInfo item) { 
        
		try
		{		
			open();
			
	        ContentValues values = new ContentValues(); 
	        
	        values.put(KeyField, item.GetKey());  
	        values.put(ValueField, item.GetValue());  
	         
	        dbHelper.db.insert(TABLE_Name, null, values); 
        
		}
		finally
		{        
			close();
		}
    } 
	
	
	public SettingInfo GetItem(String key) throws SQLException{

		try
		{
			open();
		
			SettingInfo item = null;
		
		    cursor = dbHelper.db.query(TABLE_Name,allColumns, KeyField + "='" + key +"'",null,null,null,null);	        	
    		if (cursor.moveToFirst()) 	        	
    			item =  getItemInfo(cursor);		     	       
	        
	    	return 	item;
    	
		}
		finally
		{        
			close();
		}
	   
	}
	
	 public boolean updateItem(SettingInfo item) 
	 {
		 try
		 {
		 	open();
		 	
		    ContentValues args = new ContentValues();		    
		    args.put(ValueField, item.GetValue());		    
		    boolean res =   dbHelper.db.update(TABLE_Name, args, KeyField + "='" + item.GetKey() + "'", null) > 0;
		    		    
		    return res;
	    
		}
		finally
		{        
			close();
		}
	 }
	
	
    private SettingInfo getItemInfo(Cursor cursor) {  
    	
    	SettingInfo itemInfo = new SettingInfo();    	
    	itemInfo.SetKey(cursor.getString(0)); 
    	itemInfo.SetValue(cursor.getString(1));
    	
		return itemInfo;
	}
}
